var files = [];
var uid;
var name;
var mobile;
var card;
var channel;
var number;
var summary;
var app = angular.module("applyApp", []);
app.controller("applyController", function($scope, $http) {
	$scope.apply_sub = function() {
		uid = plus.storage.getItem('uid');
		name = $('#merchant_name').val();
		mobile = $('#merchant_mobile').val();
		card_number = $('#merchant_card').val();
		channel = $("input[type='radio']:checked").val();
		number = $('#merchant_number').val();
		summary = $('#merchant_summary').val();
		upload();
	}
	
	$scope.intview = function() {
		$http({
			method: 'post',
			url: apiRoot,
			data: {
				action: 'Merchant.checkMerchantStatus',
				uid: uid
			}
		}).then(function success(result) {
			$scope.res = result.data.data;  
			$scope.is_apply = result.data.data.isapply;
		}, function errorFunction(e) {    
			plus.nativeUI.closeWaiting();
			console.log(JSON.stringify(e));
		})
	}
	
})

//资质上传
$('#goods_subject').on('tap', function() {
	plus.nativeUI.actionSheet({ cancel: "取消", buttons: [{ title: "拍照添加" }, { title: "相册添加" }] }, function(e) {
		if(e.index == 1) {
			var car = plus.camera.getCamera();
			car.captureImage(function(path) {
				path = "file://" + plus.io.convertLocalFileSystemURL(path);
				$('.img_show').append('<li class="mui-pull-left"><img src="' + path + '"><a class="iconfont mui-icon del_btn font20">&#xe603;</a></li>');
				appendpic(path, "", 2);
			}, function(err) {});

		} else if(e.index == 2) {
			plus.gallery.pick(function(path) {
				for(var i = 0; i < path.files.length; i++) {
					$('.img_show').append('<li class="mui-pull-left"><img src="' + path.files[i] + '"><a class="iconfont mui-icon del_btn font20">&#xe603;</a></li>');
					appendpic(path.files[i], "", 2);
				}
			}, function(e) {
				console.log("取消选择图片");
			}, {
				filter: "image",
				multiple: true,
				system: true,
				onmaxed: function() {
					//plus.nativeUI.alert('最多只能选择5张图片');
				}
			});
		}
	})
})

$('.upfile_box').on('click', function() {
	var id = $(this).attr('data-ind');
	plus.nativeUI.actionSheet({ cancel: "取消", buttons: [{ title: "拍照添加" }, { title: "相册添加" }] }, function(e) {
		if(e.index == 1) {
			var car = plus.camera.getCamera();
			car.captureImage(function(path) {
				path = "file://" + plus.io.convertLocalFileSystemURL(path);
				appendpic(path, id, 1)
			}, function(err) {});

		} else if(e.index == 2) {
			plus.gallery.pick(function(path) {
				appendpic(path, id, 1)
			});
		}
	})
})
//添加图片
var index = 1;
var files = [];

function appendpic(p, id, type) {
	$('#pic' + id + '>div').html('<img src="' + p + '" />');
	plus.nativeUI.showWaiting('图片处理中...');
	
	if(plus.os.name == 'Android'){
		p = plus.io.convertLocalFileSystemURL(p);		
	} 
	
	//创建新的路径
	var newpath = p.replace(/\./g, new Date().getTime() + '.');
	plus.zip.compressImage({
			src: p,
			dst: newpath,
			quality: 10
	},function() { //毁掉成功
			plus.nativeUI.closeWaiting();
			files[((parseInt(id) || 1) - 1)] = { 'patn': newpath, 'name': 'name' + id, 'type': type };
			console.log(newpath)
	},function(error) {
		alert('压缩图片失败');
		plus.nativeUI.closeWaiting();
	})
}

function upload() {
	plus.nativeUI.showWaiting('上传中...');
	var img1 = $('#pic1').find('img').length;
	var img2 = $('#pic2').find('img').length;
	var img3 = $('#pic3').find('img').length;
	var aptitude_pic = $('#goods_subject').find('img').length;
	if(!name) {
		toast('请输入姓名');
		return;
	}
	if(!mobile) {
		toast('请输入手机号码');
		return;
	}
	if(!mobile.match(p1)) {
		toast('手机号码格式不正确');
		return;
	}
	if(!card_number) {
		toast('身份证号码不能为空');
		return;
	}
	if(!card_number.match(card)) {
		toast('身份证号码格式不正确');
		return;
	}
	
//	if(!channel) {
//		toast('请选择收款方式');
//		return;
//	}

//	if($('input[type=radio]:checked').val() == undefined){
//		toast('请选择支付方式');
//		return;
//	}
//	
//	if(!number){
//		toast('请输入收款账号');
//		return;
//	} else {
//		if(!($('#merchant_number').val()).match(regx2) && !($('#merchant_number').val()).match(p1)) {
//			mui.toast('收款账号只能是手机号码或邮箱');
//			return;
//		}
//	}


	if($('#merchant_number').val() == ""){
		mui.toast('请输入收款银行卡号');return; 
	}else{
		if(!$('#merchant_number').val().match(bankCard)){
			mui.toast('银行卡号账号格式不对');return;
		}
	}
	if(img1 == 0) {
		toast('请添加本人照片');
		return;
	}
	if(img2 == 0) {
		toast('请添加本人身份证正面照片');
		return;
	}
	if(img3 == 0) {
		toast('请添加本人身份证反面照片');
		return;
	}
	if(!summary) {
		toast('请输入资质说明');
		return;
	}
	
	if($('.img_show li').length == 0){
		mui.toast('请至少上传一张资质图片');return;
	}
	var img = plus.storage.getItem('icon');
	var server = apiRoot;
	var task = plus.uploader.createUpload(server, { method: "post" },
		function(t, status) { //上传完成
			if(status == 200) {
				plus.nativeUI.closeWaiting();
				var infopics = $.parseJSON(t.responseText);
				console.log(JSON.stringify(infopics));
				if(t.responseText.data != '') {
					plus.nativeUI.toast('提交成功,请耐心等待后台审核');
					plus.webview.currentWebview().close();
					//plus.webview.create('personal_center.html', 'personal_center.html').show('pop-in');
				}
			} else {
				toast('上传失败：' + status);
				plus.nativeUI.closeWaiting();
			}
		},
		function() {
			plus.nativeUI.closeWaiting();
		}
	);
	for(var i = 0; i < files.length; i++) {
		var f = files[i];
		console.log(JSON.stringify(f));
		switch(f.type) {
			case 1:
				task.addFile(f.patn, { key: f.name });
				break;
			case 2:
				task.addFile(f.patn, { key: "zizhi" });
				break;
			default:
				break;
		}
		//		task.addFile(f.patn, { key: f.name });
	}
	task.addData('action', 'Merchant.apply');
	task.addData('uid', uid);
	task.addData('name', name);
	task.addData('mobile', mobile);
	task.addData('card', card_number);
	task.addData('channel', channel);
	task.addData('number', number);
	task.addData('summary', summary);
	task.start();
}
document.addEventListener("plusready", function() {
	appElement = document.querySelector('[ng-controller=applyController]');
	$scope = angular.element(appElement).scope();
	$scope.$apply();
})

document.addEventListener('plusready', function() {
	ws = plus.webview.currentWebview();
	uid = plus.storage.getItem('uid');
	appElement = document.querySelector('[ng-controller=applyController]');
	$scope = angular.element(appElement).scope();
	$scope.intview();
	$scope.$apply;   
})